package com.octopus.yangj.customized.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.octopus.kernal.controller.AbstractCustomizedController;
import com.octopus.kernal.controller.SearchOperator;
import com.octopus.kernal.ui.builder.DetailTableBuilder;
import com.octopus.kernal.ui.builder.QueryTableBuilder;
import com.octopus.yangj.customized.service.LogService;
import com.octopus.yangj.generated.controller.ClientValidator;
import com.octopus.yangj.generated.controller.SearchClientCommand;
import com.octopus.yangj.generated.controller.SearchEventCommand;
import com.octopus.yangj.generated.model.ClientStruct;
import com.octopus.yangj.generated.model.EventStruct;
import com.octopus.yangj.generated.service.ClientService;
import com.octopus.yangj.generated.service.EventService;

@Controller
@RequestMapping("/client/x")
public class CustomizedClientController extends AbstractCustomizedController<ClientStruct, SearchClientCommand, Long>{
	
    @Autowired
    private ClientValidator clientValidator;
    
    @Autowired
    protected ClientService clientService;
    
    @Autowired
    private EventService eventService;
    
    @Autowired
    private QueryTableBuilder<EventStruct> queryTableEventBuilder;

    @Autowired
    private DetailTableBuilder<ClientStruct> detailTableBuilder;
    
    @Autowired
    private LogService logService;
    
    @RequestMapping(value = "/create_event.o", method = RequestMethod.GET)
    public String createEvent(Model model, HttpServletRequest request, 
        @RequestParam
        Long id,
        @ModelAttribute
        ClientStruct entity) {
    	if(!SecurityUtils.getSubject().isPermitted("client:create")){
    		return "redirect:/common/unauthorized.o";
    	}
        return "redirect:/event/x/create_from_client.o?cid=" + id;
    }

	@Override
	public String saveCreate(Model model, HttpServletRequest request,
            @ModelAttribute
            ClientStruct entity, BindingResult errors) {
		String action = request.getParameter("ACTION");
		if("save_create_event".equals(action)){
	        clientValidator.validate(entity, errors);
	        if (errors.hasErrors()) {
	            return "redirect:/client/create.o";
	        }
	        try {
	            clientService.createEntity(entity);
	            logService.log("client", "create", entity.getName());
	        } catch (UncategorizedSQLException _x) {
	            _x.printStackTrace();
	            errors.rejectValue("id", "error.common.model.exist", "The entity has already existed.");
	            return "redirect:/client/create.o";
	        }
	        return "redirect:/event/x/create_from_client.o?cid=" + entity.getId();
		}
		return null;
	}

	@Override
    public String saveEdit(Model model, HttpServletRequest request,
            @RequestParam
            Long id,
            @ModelAttribute
            ClientStruct entity, BindingResult errors) {
		String action = request.getParameter("ACTION");
		if("save_create_event".equals(action)){
	        clientValidator.validate(entity, errors);
	        if (errors.hasErrors()) {
	            return "redirect:/client/edit.o";
	        }
	        try {
	            clientService.updateEntity(entity);
	            logService.log("client", "edit", entity.getName());
	        } catch (UncategorizedSQLException _x) {
	            _x.printStackTrace();
	            errors.rejectValue("id", "error.common.model.exist", "The entity has already existed.");
	            return "redirect:/client/edit.o";
	        }
	        return "redirect:/event/x/create_from_client.o?cid=" + entity.getId();
		}
		return null;
	}
	
	@RequestMapping(value = "/query_create.o", method = RequestMethod.GET)
	public String queryAndCreate(Model model, HttpServletRequest request, SearchClientCommand searchCommand) {
		String tel = request.getParameter("tel");
		if(StringUtils.isBlank(tel)){
			return "redirect:/client/query.o";
		}
		if(searchCommand.getEntity() == null){
			searchCommand.setEntity(new ClientStruct());
		}
		if(searchCommand.getOperator() == null){
			searchCommand.setOperator(new ClientStruct());
		}
		searchCommand.getEntity().setTelphone(tel);
		searchCommand.getOperator().setTelphone(String.valueOf(SearchOperator.LIKE.ordinal()));
        request.getSession().setAttribute("clientCommand", searchCommand.getEntity());
        request.getSession().setAttribute("clientOperator", searchCommand.getOperator());
        List<ClientStruct> list = clientService.search(searchCommand);
        ClientStruct entity = new ClientStruct();
        if(list == null || list.size() == 0){
        	entity.setTelphone(tel);
            model.addAttribute("ACTION", "create");
            request.setAttribute("clientDetailTable", detailTableBuilder.build(request, entity, clientValidator.getMessageSource(), false));
            request.setAttribute("clientDetailButtons", detailTableBuilder.buildButton(request, entity, clientValidator.getMessageSource(), false));
            return "customized/client/edit";
        }else if(list.size() == 1){
        	return "redirect:/client/view.o?id=" + list.get(0).getId();
        }else{
            return "redirect:/client/query.o?pager.offset=0";
        }
	}
	
    @RequestMapping(value = "/query_create.o", method = RequestMethod.POST)
    public String saveQueryAndCreate(Model model, HttpServletRequest request,
        @ModelAttribute
        ClientStruct entity, BindingResult errors) {
    	return "forward:/client/create.o";
    }
	
	@Override
	public String view(Model model, HttpServletRequest request, Long id, ClientStruct entity) {
		SearchEventCommand searchCommand = new SearchEventCommand();
		searchCommand.setEntity(new EventStruct());
		searchCommand.setOperator(new EventStruct());
		searchCommand.getEntity().setClientId(id);
		searchCommand.getOperator().setClientId(Long.valueOf(SearchOperator.EQUAL.ordinal()));
        String offset = request.getParameter("pager.offset");
        String psort = request.getParameter("field.sort");
        if (StringUtils.isNotBlank(offset)) {
            searchCommand.setOffset(Integer.parseInt(offset));
        }
        if (StringUtils.isNotBlank(psort)) {
            request.getSession().setAttribute("eventSort", psort);
        }
        Object eventSort = request.getSession().getAttribute("eventSort");
        if (eventSort!= null) {
            searchCommand.setPropertiesSorted(new String[] {eventSort.toString()});
        }
        List<EventStruct> list = eventService.search(searchCommand);
        List<String> disabledFields = new ArrayList<String>();
        disabledFields.add("client");
        disabledFields.add("_actions");
        request.setAttribute("id", id);
        request.setAttribute("events", list);
        request.setAttribute("searchCommand", searchCommand);
        request.setAttribute("eventQueryTable", queryTableEventBuilder.build(request, "Event", list, ((String) eventSort), 
        		disabledFields, "onViewEvent", "onSortEvent", clientValidator.getMessageSource()));
		return null;
	}
}
